//
//  YAYIAddMemberViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/29.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYIAddMemberViewController.h"

#import "YAYIAddMemberCell.h"
#import "YAYIMyPatientItem.h"
#import "YAYIMyPatientTool.h"

@interface YAYIAddMemberViewController () <UISearchBarDelegate>

//@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) UITableViewController *searchResultsController;
@property (nonatomic, weak) UISearchBar *searchBar;


@property (nonatomic, assign) NSInteger selectedCount;//右上角的数字

// 模拟网络数据
@property (nonatomic, strong) NSMutableArray  *serverDataArr;//数据源

@property (nonatomic, strong) NSMutableArray *patientArray;

@property (nonatomic, strong) NSArray *sectionArray;//row arr
@property (nonatomic, strong) NSArray *sectionTitleArray;//section arr
@property (nonatomic, strong) NSMutableArray *searchResultArr;

// 是否执行过搜索
@property (nonatomic, assign) BOOL isSearched;

@end

@implementation YAYIAddMemberViewController


- (void)setSelectedCount:(NSInteger)selectedCount
{
    _selectedCount = selectedCount;
    
    // 设置右上角数组
    NSString *rightBtnTitleStr = YAYIAddMemberTypeDel == self.addMemberType ? @"删除" : @"确定";
    
    NSString *rightTitle = rightBtnTitleStr;
    if (selectedCount != 0) {
        rightTitle = [NSString stringWithFormat:@"%@(%ld)", rightBtnTitleStr, selectedCount];
    }
    UIButton *rightBtn = self.navigationItem.rightBarButtonItem.customView;
    [rightBtn setTitle:rightTitle forState:UIControlStateNormal];
}

- (NSMutableArray *)searchResultArr
{
    if (nil == _serverDataArr) {
        _serverDataArr = [NSMutableArray array];
    }
    return _serverDataArr;
}


- (NSMutableArray *)patientArray
{
    if (nil == _patientArray) {
        _patientArray = [NSMutableArray array];
    }
    return _patientArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *titleStr = YAYIAddMemberTypeDel == self.addMemberType ? @"删除成员" : @"添加成员";
    self.navigationItem.title = titleStr;
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor darkGrayColor];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    self.tableView.sectionFooterHeight = 0;
    
    [self setupNav];
    
    [self setupSearchController];
    
    if (YAYIAddMemberTypeDel == self.addMemberType) {
        [self.patientArray addObjectsFromArray:self.curPatientArray];
        
        // 将数组分组
        _sectionArray = [YAYIMyPatientTool getFriendListDataBy:self.patientArray];
        // 获取组名
        _sectionTitleArray = [YAYIMyPatientTool getFriendListSectionBy:[_sectionArray mutableCopy]];
        [self.tableView reloadData];
    }else{
        [self createDataSource];
    }
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    self.tabBarController.tabBar.hidden = YES;
    
}


//- (instancetype)initWithStyle:(UITableViewStyle)style
//{
////    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)setupNav
{
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    cancelBtn.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    
    NSString *rightBtnTitleStr = YAYIAddMemberTypeDel == self.addMemberType ? @"删除" : @"确定";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:rightBtnTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


//加载搜索框
-(void)setupSearchController{
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.frame = CGRectMake(0, 0, SCREEN_width, 40);
    [[[[searchBar.subviews objectAtIndex:0] subviews] objectAtIndex : 0] removeFromSuperview];
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    self.searchBar = searchBar;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, 40)];
    view.backgroundColor = [UIColor whiteColor];
    [view addSubview:searchBar];
    self.tableView.tableHeaderView = view;
    
}


/**
 *  字典转模型
 */
- (void)setModelData
{
    for (NSDictionary *dict in self.serverDataArr)
    {
        YAYIMyPatientItem *model = [[YAYIMyPatientItem alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [self.patientArray addObject:model];
    }
    
    _sectionArray = [YAYIMyPatientTool getFriendListDataBy:self.patientArray];
    
    _sectionTitleArray = [YAYIMyPatientTool getFriendListSectionBy:[_sectionArray mutableCopy]];
}


#pragma mark - 获取数据
- (void)createDataSource
{
    // 显示hud
    [SVProgressHUD show];
    
    [self.patientArray removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"tagid"] = self.tagID;
    param[@"isadd"] = @"Y";
    
    [YAYINetWorking getWithURL:patienList_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                
                NSArray *data = dict[@"data"];
                
                for (NSDictionary *obj in data) {
                    YAYIMyPatientItem *item = [YAYIMyPatientItem new];
                    [item setValuesForKeysWithDictionary:obj];
                    
                    [self.patientArray addObject:item];
                }
                
                _sectionArray = [YAYIMyPatientTool getFriendListDataBy:self.patientArray];
                YAYILog(@"_sectionArray:%@", _sectionArray);
                
                _sectionTitleArray = [YAYIMyPatientTool getFriendListSectionBy:[_sectionArray mutableCopy]];
                YAYILog(@"_sectionArr:%@", _sectionTitleArray);
                
                [self.tableView reloadData];
            }
            
            
            //            if (0 == self.appointArray.count) {
            //                [self showNoDataFlag:YES];
            //
            //            }else{
            //                [self showNoDataFlag:NO];
            //            }
        }else{
            
            YAYILog(@"erro:%@", error);
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
    
}


#pragma mark - 点击事件方法
- (void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)cancelAction:(UIButton *)sender
{
    YAYILog(@"点击了取消");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sureAction:(UIButton *)sender
{
    YAYILog(@"点击了保存");
    
    NSMutableArray *selectedArray = [NSMutableArray array];
    NSMutableArray *notSelectedArray = [NSMutableArray array];
    
    for (NSArray *array in self.sectionArray) {
        for (YAYIAddMemberCell *model in array) {
            if (model.isSelected) {
                model.isSelected = NO;
                [selectedArray addObject:model];
            }else{
                [notSelectedArray addObject:model];
            }
        }
    }
    
    
    if (YAYIAddMemberTypeDel == self.addMemberType) {
        
        if (self.isNew) {
            
            if ([self.delegate respondsToSelector:@selector(addMemberBy:notSelectedArray:)]) {
                [self.delegate addMemberBy:selectedArray notSelectedArray:notSelectedArray];
                [self goBack];
            }
        }else{
            [self delPatient:selectedArray];
        }
    }else{
        
        [self addPatient:selectedArray];
    }
}


- (void)addPatient:(NSMutableArray *)selectedArray
{
    YAYILog(@"点击了添加");
    
    NSMutableString *patientIDs = [NSMutableString string];
    
    for (int i = 0; i < selectedArray.count; i++) {
        YAYIMyPatientItem *model = selectedArray[i];
        [patientIDs appendFormat:@"%ld", model.dcid];
        if (i != selectedArray.count - 1) {
            [patientIDs appendString:@","];
        }
    }
    
    if (YAYIAddMemberTypeNew == self.addMemberType) {
        
        if ([self.delegate respondsToSelector:@selector(addMemberBy:)]) {
            [self goBack];
            [self.delegate addMemberBy:selectedArray];   
        }
        
    }else{
    
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"tagid"] = self.tagID;
        param[@"dcids"] = patientIDs;
        
        YAYILog(@"parm:%@", param);
        
        [YAYINetWorking postJsonSerilizeWithURL:patienAddTagGroup_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
            if (error == nil) {
                YAYILog(@"保存标签：%@", dict);
                
                if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                    [SVProgressHUD showWithStatus:@"保存失败"];
                    
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self goBack];
                        // 执行代理刷新上级控制器
                        
                    });
                }
            }else{
                NSString *message = responseError[@"message"];
                 [SVProgressHUD showWithStatus:message];
            }
        }];
    }
    
    
}

- (void)delPatient:(NSMutableArray *)selectedArray
{
    YAYILog(@"点击了删除");
    
    NSMutableString *patientIDs = [NSMutableString string];
    
    for (int i = 0; i < selectedArray.count; i++) {
        YAYIMyPatientItem *model = selectedArray[i];
        [patientIDs appendFormat:@"%ld", model.dcid];
        if (i != selectedArray.count - 1) {
            [patientIDs appendString:@","];
        }
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"tagid"] = self.tagID;
    param[@"dcids"] = patientIDs;
    
    YAYILog(@"parm:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:patienDelTagGroup_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
            YAYILog(@"保存标签：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                [SVProgressHUD showWithStatus:@"删除失败"];
                
            }else{
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self goBack];
                    // 执行代理刷新上级控制器
                    
                });
            }
        }else{
            NSString *message = responseError[@"message"];
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}


#pragma mark - 工具方法
- (void)filterContentForSearchText:(NSString*)searchText
{
    NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
    
    [self.searchResultArr removeAllObjects];
    for (int i = 0; i < self.patientArray.count; i++) {
        YAYIMyPatientItem *model = self.patientArray[i];
        NSString *nameStr = model.clientname;
        NSString *pinyinStr = model.pinyin;
        
        NSRange nameRange = [nameStr rangeOfString:searchText options:searchOptions];
        NSRange pinyinRange = [pinyinStr rangeOfString:searchText options:searchOptions];

        
        if (nameRange.length || pinyinRange.length)
        {
            [self.searchResultArr addObject:model];
        }
        
    }

    YAYILog(@"self.searchResultArr:%@", self.searchResultArr);
}


#pragma mark - 代理方法
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.isSearched) {
        return 0;
    }
    return 22.0;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //viewforHeader
    id label = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14.5f]];
        
        [label setTextColor:[UIColor grayColor]];
//        [label setBackgroundColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1]];
    }
    
    [label setText:[NSString stringWithFormat:@"  %@",self.sectionTitleArray[section + 1]]];
    
    return label;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.isSearched) {
        return 1;
    }else{
        return _sectionArray.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSearched) {
        return self.searchResultArr.count;
    }else{
        return [self.sectionArray[section]  count];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 50.0;
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.isSearched) {
        return nil;
    }else{
        return self.sectionTitleArray;
        
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index - 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YAYIAddMemberCell *cell = [YAYIAddMemberCell cellWith:tableView];
    
    if (self.isSearched) {
        YAYIMyPatientItem *model = self.searchResultArr[indexPath.row];
        cell.item = model;
        
        // 判断使用什么线
        if (indexPath.row == 0) {
            cell.lineType = LineTypeTop;
        }else{
            cell.lineType = LineTypeBottom;
            
        }
        
        
    }else{
        YAYIMyPatientItem *model = self.sectionArray[indexPath.section][indexPath.row];
        cell.item = model;
        
        // 判断使用什么线
        if (indexPath.row == 0) {
            cell.lineType = LineTypeTop;
        }else if (indexPath.row == [self.sectionArray[indexPath.section] count] - 1){
            cell.lineType = LineTypeBottom;
        }else{
            cell.lineType = LineTypeCenter;
        }
    }
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YAYIMyPatientItem *model = nil;
    if (self.isSearched) {
        model = self.searchResultArr[indexPath.row];
    }else{
        model = self.sectionArray[indexPath.section][indexPath.row];
    }
    
    model.isSelected = !model.isSelected;
    
    YAYIAddMemberCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.isSelected = model.isSelected;
    
    if (model.isSelected) {
        self.selectedCount++;
    }else{
        self.selectedCount--;
    }

}

#pragma  mark searchController delgate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;{
    //    NSString *filterString = searchController.searchBar.text;
    //
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c] %@", filterString];
    //    self.searchArry = [NSMutableArray arrayWithArray:[self.tableArry filteredArrayUsingPredicate:predicate]];
    //    //    UITableViewController *searchTableController=(UITableViewController *)searchController;
    //    [self.searchResultsController.tableView reloadData];
}

- (void)willPresentSearchController:(UISearchController *)searchController
{
    self.tabBarController.tabBar.hidden = YES;
}


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //    self.tabBarController.tabBar.hidden = YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.searchController.searchBar.mj_y = 64;
    }];
    
    
    return YES;
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text.length > 0) {
        self.isSearched = YES;
        YAYILog(@"searchBar.text:%@", searchBar.text);
        [self filterContentForSearchText:searchBar.text];
        [self.tableView reloadData];
    }else{
        self.isSearched = NO;
        [self.tableView reloadData];
    }
}


@end
